package com.modules.user.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.common.response.ResponseVO;
import com.common.exception.RRException;
import com.common.utils.R;
import com.modules.user.entity.UserEntity;
import com.modules.user.service.IUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    // 登录
    @PostMapping("/login")
    public R doLogin(@RequestBody UserEntity user){
        return userService.doLogin(user);
    }

    // 退出
    @PostMapping("/loginOut")
    public R loginOut(@RequestBody UserEntity user){
        return userService.loginOut(user);
    }

    // 修改密码
    @PostMapping("/modifyPass")
    public R modifyPass(@RequestBody Map<String, Object> params){
        return userService.modifyPass(params);
    }

    // 用户分页列表
    @RequestMapping("/getPageList")
    public R getPageList(@RequestHeader("token")String token, @RequestParam Map<String, Object> params){
        params.put("token", token);
        return userService.getPageList(params);
    }

    // 代理商用户分页列表
    @RequestMapping("/getAgentPageList")
    public R getAgentPageList(@RequestParam Map<String, Object> params){
        return userService.getAgentPageList(params);
    }

    // 获得单个用户信息
    @GetMapping ("/getEntityById/{id}")
    public R getEntityById(@PathVariable Integer id){
        UserEntity userEntity = userService.getOne(new QueryWrapper<UserEntity>().lambda().eq(UserEntity::getId, id));
        if (userEntity == null){
            throw new RRException("用户不存在");
        }
        return R.ok().put("data", userEntity);
    }

    // 添加/修改 用户
    @PostMapping("/saveEntity")
    public R saveEntity(@RequestHeader("token")String token, @RequestBody UserEntity userEntity){
        // 根据当前人的token找到用户
        UserEntity user = userService.getOne(new LambdaQueryWrapper<UserEntity>()
                .eq(UserEntity::getToken, token));
        if (user == null){
            return R.error("找不到操作人");
        }

		// 查重
		UserEntity userData = userService.getOne(new QueryWrapper<UserEntity>().lambda()
				.eq(UserEntity::getUsername, userEntity.getUsername())
				.ne(userEntity.getId() != null, UserEntity::getId, userEntity.getId())
		);
		if (userData != null){
			throw new RRException("账号已存在");
		}

		// 如果是新增
        if (userEntity.getId() == null){
			// 如果是代理商添加用户，判断下级是否有超过数量
			if (user.getType() == 2){
				int childCount = userService.count(new LambdaQueryWrapper<UserEntity>()
						.eq(UserEntity::getCreateBy, user.getId()));
				if (childCount >= user.getChildNum()){
					return R.error("下级账号已达上限");
				}
			}
			userEntity.setCreateBy(user.getId());
			userEntity.setCreateTime(new Date());
			userService.save(userEntity);
		}
        // 如果是修改
        else {
        	userService.updateById(userEntity);
		}

		// 如果是管理员操作的是代理商信息，并且代理商的密码为空，则设置默认密码为123456
		UserEntity newUserEntity = userService.getById(userEntity.getId());
		if (newUserEntity.getType() != null && newUserEntity.getType() == 2 && StringUtils.isBlank(newUserEntity.getPassword())){
			String password = SecureUtil.sha1( SecureUtil.md5("123456"));
			newUserEntity.setPassword(password);
			userService.updateById(newUserEntity);
		}
        return R.ok();
    }

    // 删除用户
    @DeleteMapping("/removeEntity/{id}")
    public R removeEntity(@PathVariable Integer id){
        UserEntity userEntity = userService.getOne(new QueryWrapper<UserEntity>().lambda().eq(UserEntity::getId, id));
        if (userEntity == null){
            throw new RRException("用户不存在");
        }
        // 如果删除的是代理商，就把代理商的下级移到管理员里
        if (userEntity.getType() == 2){
			List<UserEntity> childList = userService.list(new LambdaQueryWrapper<UserEntity>()
				.eq(UserEntity::getCreateBy, userEntity.getId()));
			if (CollectionUtil.isNotEmpty(childList)){
				for (UserEntity childUser: childList){
					childUser.setCreateBy(1);
					userService.updateById(childUser);
				}
			}
		}
        userService.removeById(userEntity);
        return R.ok();
    }
}
